package com.example.demo.ui.home

import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.demo.R
import com.example.demo.databinding.ActivityVideoBinding
import com.example.demo.model.BaseBean
import com.example.demo.model.ChannelBean
import com.example.demo.model.VideoBean
import com.example.demo.ui.home.adapter.OnChannelItemClickListener
import com.example.demo.ui.home.adapter.OnItemClickListener
import com.example.demo.ui.home.adapter.VideoListAdapter
import com.example.demo.util.MyJson
import com.example.demo.util.ToastUtil
import com.google.gson.reflect.TypeToken
import android.os.Bundle as Bundle1

class VideoActivity : AppCompatActivity(), OnChannelItemClickListener, OnItemClickListener {
    private lateinit var binding: ActivityVideoBinding

    override fun onCreate(savedInstanceState: Bundle1?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_video)

        val json = loadJsonFromAsset("Video.json")
//        val baseBean = Gson().fromJson(json, object : TypeToken<BaseBean<List<VideoBean>>>() {}.type)
//        val videos: List<VideoBean> = baseBean.getData()

        val baseBean = MyJson.fromJson<BaseBean<*>>(json, BaseBean::class.java)

        val videos = MyJson.toJson(baseBean.getData())?.let {
            MyJson.fromJson<List<VideoBean>>(
                it,
                object : TypeToken<ArrayList<VideoBean?>?>() {}.type
            )
        }

        binding.videoRecyclerView.layoutManager = LinearLayoutManager(this)
        binding.videoRecyclerView.adapter = videos?.let { VideoListAdapter(it, this,this) }
    }

    override fun onChannelItemClicked(channel: ChannelBean) {
        // 在这里处理频道点击事件
        ToastUtil.showLong("测试点击事件！")
    }

    override fun onItemClicked(video: VideoBean, isExpanded: Boolean) {
        // 数据为空提示
        if (video.channels == null || video.channels.isEmpty() && isExpanded) {
            ToastUtil.showLong("没有要学习的视频！")
        }

        // 在这里处理视频项点击事件
        if (isExpanded) {
            // 处理展开逻辑
        } else {
            // 处理合上逻辑
        }
    }

    private fun loadJsonFromAsset(fileName: String): String {
        return assets.open(fileName).bufferedReader().use { it.readText() }
    }
}